//import { BuffData } from "./BuffData";
import { attributePointsPerLevel, attributePointsPerUpgrade } from "./Config/Config";
import { EBaseAttribute, EEvent, EPlayerType, ESkill, EWuxing } from "./Config/Enum";

import { PlayerConfig } from "./Config/PlayerConfig";
import { EPassiveSkill } from "./Config/SkillConfig";
import { Core } from "./Core/Core";
import { EquipmentData } from "./Item/EquipmentData";
import { EAffixType } from "./Item/Item";
import { PetData } from "./PetData";
import { SkillData } from "./Skill/SkillData";
import { Util } from "./Util";

export interface IPlayerData {
    level: number;
    wuxing: EWuxing;
    exp: number;
    expToNextLevel: number
    
    attributePoints: number;
    skillPoints: number;
    strength: number;
    agility: number;
    intelligence: number;
    innerPower: number;
    vitality: number;
    primaryAttribute: EBaseAttribute;
    attributeGrowth: number[];

    // 普通词缀可能加的属性
    ap: number;
    dp: number;
    hp: number;
    accuracy: number; // 添加命中率属性
    speed: number;
    attackRange: number;
    attackSpeed: number;
    criticalChance: number;
    criticalDamage: number;
    wuxingEnhance: number;
    skillEnhance: number;
    ComboChance:number
    penetrateCount: number; // 穿透
    penetratePercent: number; // 穿透伤害
    ignoreDefense: number;
    CDR:number
    dodge:number
    skillLevel:number
    hpRegen: number;
    skill1Level: number;
    skill2Level: number;
    skill3Level: number;

    moreCoin: number;
    moreReown: number;
    moreExp: number;
    MF:number;

    rageRegen: number;
    //ragePerAttack: number;
    rageMax: number;
    skillData: SkillData;
    //buffData: BuffData;
    skillPointLeft: number;
    skillPointTotal: number;
    equipmentData: EquipmentData;
    playerType: EPlayerType;
    potentialPoints: number[]

    skillDamage:number


}

export const EPlayerDataUpdateEvent = {
    AP_Changed: "AP_Changed",
    DP_Changed: "DP_Changed",
};

export class PlayerData implements IPlayerData {
    playerType: EPlayerType;
    config: any;
    equipmentStats: any;
    equipmentStats_wuxingStats: any;


    level: number = 0;
    exp: number = 0;
    expToNextLevel: number = 0;
    attributePoints: number = 0;
    skillPoints: number = 0;

    wuxing: EWuxing = EWuxing.Jin;
    skillPointLeft: number = 0;
    skillPointTotal: number = 0;
    //: number = 5;
    rageMax: number = 100;
    strength: number = 10;
    agility: number = 10;
    intelligence: number = 10;
    innerPower: number = 10;
    vitality: number = 10;

    strength_noEquip: number = 10;
    agility_noEquip: number = 10;
    intelligence_noEquip: number = 10;
    innerPower_noEquip: number = 10;
    vitality_noEquip: number = 10;
    primaryAttribute: EBaseAttribute;
    attributeGrowth: number[] = [2.5, 1.5, 1, 1, 2];
    // 普通词缀可能加的属性
    ap: number = 10;
    dp: number = 10;
    hp: number = 0;
    accuracy: number = 1; // 命中率，默认100%
    speed: number = 0;
    attackRange: number = 0;
    attackSpeed: number = 0;
    criticalChance: number = 0;
    criticalDamage: number = 1.5;
    wuxingEnhance: number = 0;
    penetrateCount: number = 0; // 穿透
    penetratePercent: number = 0; // 穿透伤害
    ignoreDefense: number=0;
    skillEnhance: number = 0; // 武学增强
    CDR:number=0
    dodge:number=0
    ComboChance:number=0
    skillLevel:number=0
    hpRegen: number = 0;
    skill1Level: number;
    skill2Level: number;
    skill3Level: number;
    rageRegen: number=0;
    
    
    moreCoin: number=0;
    moreReown: number=0;
    moreExp: number=0;
    MF:number=0;

    potentialPoints: number[] = [0, 0, 0, 0, 0]; // 力量、身法、悟性、体质、内功

    skillData: SkillData;
    //buffData: BuffData;
    equipmentData: EquipmentData;
    isLevelUp: boolean = false; // 是否升级
    skillDamage: number=0;
    //petData: PetData;

    constructor(playerType: EPlayerType) {
        this.playerType = playerType;
        this.config = PlayerConfig[playerType];
        this.equipmentStats = {};

        const config = PlayerConfig[playerType];
        Object.assign(this, {
            level: config.level,
            exp:0,
            expToNextLevel:0,
            attributePoints: 0,
            skillPoints: 0,
            wuxing: config.wuxing,
            skillPointLeft: 0,
            skillPointTotal: 0,
            rageMax: config.rageMax,
            //ragePerAttack: config.ragePerAttack,
            strength: config.strength,
            agility: config.agility,
            intelligence: config.intelligence,
            innerPower: config.innerPower,
            vitality: config.vitality,
            primaryAttribute: config.primaryAttribute,
            attributeGrowth: config.attributeGrowth || [2.5, 1.5, 1, 1, 2],
            ap: config.ap,
            dp: config.dp,
            hp: config.hp,
            accuracy: config.accuracy || 1, // 默认100%命中率
            speed: config.speed,
            attackRange: config.attackRange,
            attackSpeed: config.attackSpeed,
            criticalChance: config.criticalChance,
            criticalDamage: config.criticalDamage,
            wuxingEnhance: config.wuxingEnhance,
            penetratePercent: config.penetratePercent || 0,
            penetrateCount: config.penetrateCount || 0,
            skillEnhance: 0,
            ComboChance:0,
            rageRegen:1,
            skill1Level:0,
            skill2Level:0,
            skill3Level:0,
            moreCoin:0,
            moreReown:0,
            moreExp:0,
            MF:0,
            CDR:0,
            ignoreDefense:0,
            hpRegen:0,
            skillDamage:0,
            skillLevel:0,
            dodge:0,
            potentielPoints: [0, 0, 0, 0, 0], // 力量、身法、悟性、体质

        });

        this.skillData = new SkillData(playerType);
        //this.petData = new PetData();
        //this.buffData = new BuffData();
        this.equipmentData = new EquipmentData(playerType);
        this.initExperienceSystem();
        this.calculateAttributes();
    }


        // 初始化修为系统
    initExperienceSystem() {
        this.calculateExpToNextLevel();
    }

        // 添加修为值
    addExp(amount: number) {
        this.exp += amount;
        // 检查是否升级
        while (this.exp >= this.expToNextLevel && this.level < 100) { // 假设最大100级
            this.levelUp();
        }
    }

    getHp(): number {
        return this.hp;
    }
    
    getDp(): number {
        return this.dp;
    }

    getDodge(){
        return this.dodge;
    }


    // 升级逻辑
    levelUp() {
        this.exp -= this.expToNextLevel; // 扣除升级所需修为
        this.level++;
        this.isLevelUp = true; // 标记为升级状态
        
        // 每级获得5属性点和1武学点
        this.attributePoints+= attributePointsPerLevel // 每升一级增加的属性点数
        this.skillPoints++;
        // emit事件 active红点
        //Core.Instance.event.emit(EEvent.PlayerLevelUp);
        
        // 重新计算下一级所需修为
        this.calculateExpToNextLevel();
        
        // 根据职业增长基础属性
        this.growBaseAttributes();
    }

        // 根据职业增长基础属性
    growBaseAttributes() {
        const config = PlayerConfig[this.playerType];
        if (!config) return;
        
        const growth = config.attributeGrowth;
        this.strength += growth[0];
        this.agility += growth[1];
        this.intelligence += growth[2];
        this.innerPower += growth[3];
        this.vitality += growth[4];
        
        // 更新属性
        this.calculateAttributes()
        Core.Instance.save()

    }

        // 分配武学点
    assignSkillPoint(skill: ESkill) {
        if (this.skillPoints <= 0) {
            // 去除红点

            return
        }
        
        // 这里需要实现武学升级逻辑
        this.skillData.upgradeSkill(skill);
        this.skillPoints--;
    }

    // 手动分配属性点
    upgradeAttribute(attribute: EBaseAttribute) {
        console.log("升级属性:", attribute, "当前属性点:", this.attributePoints);
        if (this.attributePoints <= 0) {
            //console.error("属性点不足，无法升级");
            this.attributePoints = 0; // 确保属性点不为负
            return;
        }
        if (this.attributePoints <= attributePointsPerUpgrade) {
            switch (attribute as EBaseAttribute) {
                case EBaseAttribute.Strength:
                    //this.strength += this.attributePoints;
                    this.potentialPoints[0] += this.attributePoints; // 力量
                    console.log("升级力量属性:", this.strength);
                    break;
                case EBaseAttribute.Agility:
                    //this.agility += this.attributePoints;
                    this.potentialPoints[1] += this.attributePoints; // 身法
                    break;
                case EBaseAttribute.Intelligence:
                    //this.intelligence += this.attributePoints;
                    this.potentialPoints[2] += this.attributePoints; // 悟性
                    break;
                case EBaseAttribute.Vitality:
                    //this.vitality += this.attributePoints;
                    this.potentialPoints[3] += this.attributePoints; // 体质
                    break;
                case EBaseAttribute.InnerPower:
                    //this.innerPower += this.attributePoints;
                    this.potentialPoints[4] += this.attributePoints; // 内力
                    break;
                default:
                    console.error("未知属性类型:", attribute);
                    return;
            }
            this.attributePoints = 0; // 使用完所有属性点
            Core.Instance.event.emit(EEvent.PlayerDataChange); // 通知其他组件更新属性显示

        }else{
            switch (attribute  as EBaseAttribute) {
                case EBaseAttribute.Strength:
                    this.potentialPoints[0] += attributePointsPerUpgrade;

                    break;
                case EBaseAttribute.Agility:
                    this.potentialPoints[1] += attributePointsPerUpgrade;
                    break;
                case EBaseAttribute.Intelligence:
                    this.potentialPoints[2] += attributePointsPerUpgrade;
                    break;
                case EBaseAttribute.Vitality:
                    this.potentialPoints[3] += attributePointsPerUpgrade;
                    break;
                case EBaseAttribute.InnerPower:
                    this.potentialPoints[4] += attributePointsPerUpgrade;
                    break;
                default:
                    console.error("未知属性类型:", attribute);
                    return;
            }
            this.attributePoints -= attributePointsPerUpgrade;
            Core.Instance.event.emit(EEvent.PlayerDataChange); // 通知其他组件更新属性显示
            
        }

        Core.Instance.save()

        
    }

    // 重置所有手动分配的属性点
    resetAttributes() {
        this.attributePoints += this.potentialPoints.reduce((a, b) => a + b, 0);
        this.potentialPoints = [0, 0, 0, 0, 0];
        this.calculateAttributes(true);
        Core.Instance.save()
    }



    // 计算升级所需修为 (二次增长曲线)
    calculateExpToNextLevel() {
    // 基础修为值 * 等级^1.5
        this.expToNextLevel = Math.floor(100 * Math.pow(this.level, 1.5));
    }

    // 计算属性
    calculateAttributes(sendEvent: boolean = false) {
        console.log("属性异常排查 - calculateAttributes开始");
        this.calBaseAttribute(); // 计算基础属性
        this.calAttributeWithPassiveSkill(); // 被动技能加成
        this.calAttributeWithPet();  // 宠物加成
        this.calEquipmentData(); // 计算装备属性
        this.calAttributeWithEquip(); // 基础属性合并装备加成
        this.calSecondaryAttribute(); // 计算二级属性（AP、DP等）
        this.calSecondaryAttributeWithPassiveSkill(); // 被动技能加成
        console.log("属性异常排查 - calculateAttributes结束，最终AP:", this.ap, "最终DP:", this.dp);
        //Core.Instance.save()

        if (sendEvent) {
            Core.Instance.event.emit(EEvent.PlayerDataUpdated);
        }

    }

    // 计算基础属性(不包含装备)
    calBaseAttribute(){
        // this.strength_noEquip = this.config.strength + this.level * this.config.attributeGrowth[0] || 0;
        // this.agility_noEquip = this.config.agility + this.level * this.config.attributeGrowth[1] || 0;
        // this.intelligence_noEquip = this.config.intelligence + this.level * this.config.attributeGrowth[2] || 0;
        // this.vitality_noEquip = this.config.vitality + this.level * this.config.attributeGrowth[3] || 0;
        // this.innerPower_noEquip = this.config.innerPower + this.level * this.config.attributeGrowth[4] || 0;
        this.strength = this.config.strength + this.level * this.config.attributeGrowth[0] + this.potentialPoints[0]
        this.agility = this.config.agility + this.level * this.config.attributeGrowth[1] + this.potentialPoints[1]
        this.intelligence = this.config.intelligence + this.level * this.config.attributeGrowth[2] + this.potentialPoints[2]
        this.vitality = this.config.vitality + this.level * this.config.attributeGrowth[3] + this.potentialPoints[3]
        this.innerPower = this.config.innerPower + this.level * this.config.attributeGrowth[4] + this.potentialPoints[4]

        console.log("属性异常排查 - calBaseAttribute: 力量=", this.strength, "敏捷=", this.agility, "智力=", this.intelligence, "体质=", this.vitality, "内功=", this.innerPower);
        console.log("属性异常排查 - calBaseAttribute: 等级=", this.level, "潜力点=", this.potentialPoints);

        //console.log("宠物calBaseAttribute,this.agility",this.agility, this.config.agility, this.level, this.config.attributeGrowth[1])

    }
    // 某些被动技能会影响基础属性。例如少林易筋经+5%基础属性。
    calAttributeWithPassiveSkill(){
        if(this.playerType == EPlayerType.Shaolin && this.skillData.assignedPassiveSkill == EPassiveSkill.ShaolinPassive1){
            console.log("属性异常排查 - 少林易筋经被动技能加成5%基础属性触发，加成前： 力量=", this.strength, "敏捷=", this.agility, "智力=", this.intelligence, "体质=", this.vitality);
            this.strength *= 1.2;
            this.agility *= 1.2;
            this.intelligence *= 1.2;
            this.vitality *= 1.2;
            //this.innerPower *= 1.05;
            console.log("属性异常排查 - 少林易筋经被动技能加成后: 力量=", this.strength, "敏捷=", this.agility, "智力=", this.intelligence, "体质=", this.vitality);
        }

    }
    calAttributeWithPet(){
        console.log("属性异常排查 - calAttributeWithPet开始: 力量=", this.strength, "敏捷=", this.agility, "智力=", this.intelligence);

        Core.Instance.pets.forEach((petData, petType) => {
            if (petData.assigned){
                const oldStrength = this.strength;
                const oldAgility = this.agility;
                const oldIntelligence = this.intelligence;
                
                this.strength *= (1 + petData.strength);
                this.agility *= (1 + petData.agility);
                this.intelligence *= (1 + petData.intelligence);
                
                console.log(`属性异常排查 - 宠物${petType}加成: 力量 ${oldStrength} -> ${this.strength}, 敏捷 ${oldAgility} -> ${this.agility}, 智力 ${oldIntelligence} -> ${this.intelligence}`);
            }

        })

        console.log("属性异常排查 - calAttributeWithPet结束: 力量=", this.strength, "敏捷=", this.agility, "智力=", this.intelligence);

        //console.log("宠物calAttribute WithPet this.agility", this.agility)



    }
    calEquipmentData() {
        console.log("属性异常排查 - calEquipmentData开始");
        //console.log("calEquipmentData,this.equipmentStats",this.equipmentStats)
            //     if(this.equipmentStats.length == 0){
            // console.log("this.equipmentStats is null")
            // return}
        const equipmentStats = this.equipmentData.calculateTotalEquipmentStats();
        this.equipmentStats = equipmentStats.normalStats;
        this.equipmentStats_wuxingStats = equipmentStats.wuxingStats;
        
        console.log("属性异常排查 - 普通装备属性:", this.equipmentStats);
        console.log("属性异常排查 - 五行装备属性:", this.equipmentStats_wuxingStats);
        console.log("属性异常排查 - 关键装备属性: 攻击=", this.equipmentStats[EAffixType.Attack], "防御=", this.equipmentStats[EAffixType.Defense], "力量=", this.equipmentStats[EAffixType.Strength]);

        //console.log("calEquipmentData,this.equipmentStats",this.equipmentData.calculateTotalEquipmentStats())
        //console.log("calEquipmentData,this.equipmentStats2",this.equipmentData.calculateTotalEquipmentStats().normalStats)
        //console.log("calEquipmentData,this.equipmentStats3",this.equipmentData.calculateTotalEquipmentStats().wuxingStats)

    }

    // 计算基础属性（包含装备）
    calAttributeWithEquip() {
        console.log("属性异常排查 - calAttributeWithEquip开始: 力量=", this.strength, "敏捷=", this.agility, "智力=", this.intelligence);

        const oldStrength = this.strength;
        const oldAgility = this.agility;
        const oldIntelligence = this.intelligence;
        const oldVitality = this.vitality;
        const oldInnerPower = this.innerPower;

        this.strength = this.strength + this.equipmentStats[EAffixType.Strength] + this.equipmentStats[EAffixType.AllBaseAttributes];
        this.agility = this.agility + this.equipmentStats[EAffixType.Agility] + this.equipmentStats[EAffixType.AllBaseAttributes];
        this.intelligence = this.intelligence + this.equipmentStats[EAffixType.Intelligence]+this.equipmentStats[EAffixType.AllBaseAttributes];
        this.vitality = this.vitality + this.equipmentStats[EAffixType.Vitality] + this.equipmentStats[EAffixType.AllBaseAttributes];
        this.innerPower = this.innerPower + this.equipmentStats[EAffixType.InnerPower]  || 0;

        console.log("属性异常排查 - calAttributeWithEquip结束:");
        console.log("属性异常排查 - 力量:", oldStrength, "->", this.strength, `(+${this.equipmentStats[EAffixType.Strength]}装备 +${this.equipmentStats[EAffixType.AllBaseAttributes]}全属性)`);
        console.log("属性异常排查 - 敏捷:", oldAgility, "->", this.agility, `(+${this.equipmentStats[EAffixType.Agility]}装备 +${this.equipmentStats[EAffixType.AllBaseAttributes]}全属性)`);
        console.log("属性异常排查 - 智力:", oldIntelligence, "->", this.intelligence, `(+${this.equipmentStats[EAffixType.Intelligence]}装备 +${this.equipmentStats[EAffixType.AllBaseAttributes]}全属性)`);
        console.log("属性异常排查 - 体质:", oldVitality, "->", this.vitality, `(+${this.equipmentStats[EAffixType.Vitality]}装备 +${this.equipmentStats[EAffixType.AllBaseAttributes]}全属性)`);
        console.log("属性异常排查 - 内功:", oldInnerPower, "->", this.innerPower, `(+${this.equipmentStats[EAffixType.InnerPower]}装备)`);

        //console.log("宠物calBaseAttribute withequip,this.agility", this.agility)
    }


calSecondaryAttribute() {
    console.log("属性异常排查 - calSecondaryAttribute开始");
    console.log("属性异常排查 - 当前基础属性: 力量=", this.strength, "敏捷=", this.agility, "智力=", this.intelligence, "体质=", this.vitality, "内功=", this.innerPower);
    console.log("属性异常排查 - 主属性:", this.primaryAttribute);

    // 获取主属性值
    const primaryValue = {
        [EBaseAttribute.Strength]: this.strength,
        [EBaseAttribute.Agility]: this.agility,
        [EBaseAttribute.Intelligence]: this.intelligence,
        [EBaseAttribute.Vitality]: this.vitality
    }[this.primaryAttribute]||0;

    console.log("属性异常排查 - 主属性值:", primaryValue);

    // 1. 攻击力(AP)公式 - 主属性 + 副属性 加成不一样
    let baseAp = this.config.ap + this.level * 1; // 基础攻击力 + 每级增加1点
    // 主属性对攻击力的影响
    let apFromPrimary  = primaryValue * 1; // 主属性每点增加0.5AP
    // 去掉主属性，其他属性对攻击力的影响
    // 计算其他属性贡献（排除主属性）
    let apFromOtherAttributes = 0;
    switch(this.primaryAttribute) {
        case EBaseAttribute.Strength:
            apFromOtherAttributes = 
                (this.agility + this.intelligence) * 0.2;
            break;
        case EBaseAttribute.Agility:
            apFromOtherAttributes = 
                (this.strength + this.intelligence ) * 0.2;
            break;
        case EBaseAttribute.Intelligence:
            apFromOtherAttributes = 
                (this.strength + this.agility ) * 0.2;
            break;
        // case EBaseAttribute.Vitality:
        //     apFromOtherAttributes =
        //         (this.strength + this.agility + this.intelligence) * 0.2;
        //     break;
        default:
            // 如果主属性不是以上3种，则所有属性都按0.5计算
            apFromOtherAttributes = 
                (this.strength + this.agility + this.intelligence) * 0.5;
            break;
    }

    // 最终攻击力计算
    const apBeforeEquipment = baseAp + apFromPrimary + apFromOtherAttributes;
    this.ap = apBeforeEquipment;
    
    console.log("属性异常排查 - AP计算详情:");
    console.log("属性异常排查 - 基础AP:", baseAp, "主属性加成:", apFromPrimary, "其他属性加成:", apFromOtherAttributes);
    console.log("属性异常排查 - 装备前AP:", apBeforeEquipment);


    // 2. 生命值(HP)公式
    const hpBeforeEquipment = this.config.hp + 
              this.vitality * 15 +  // 体质对生命值贡献提升
              this.innerPower * 5 + 
              this.strength * 2;
    this.hp = hpBeforeEquipment;

    // 3. 防御力(DP)公式
    const dpBeforeEquipment = this.config.dp + 
              this.vitality * 1.2 + 
              this.strength * 0.8 + 
              this.innerPower * 0.6;
    this.dp = dpBeforeEquipment;

    console.log("属性异常排查 - HP计算: 基础", this.config.hp, "+ 体质", this.vitality*15, "+ 内功", this.innerPower*5, "+ 力量", this.strength*2, "=", hpBeforeEquipment);
    console.log("属性异常排查 - DP计算: 基础", this.config.dp, "+ 体质", this.vitality*1.2, "+ 力量", this.strength*0.8, "+ 内功", this.innerPower*0.6, "=", dpBeforeEquipment);

    // 4. 攻速公式 - 使用攻击间隔（秒）
    const baseAttackInterval = this.config.attackSpeed; // 基础攻击间隔
    
    // 核心公式：攻击间隔 = 基础攻击间隔 / (1 + 敏捷系数)
    let attackInterval = baseAttackInterval / (1 + this.agility * 0.02);
    
    // 力量对攻速的负面影响
    attackInterval *= (1 + this.strength * 0.005);
    
    // 装备提供的攻速加成（减少攻击间隔）
    const equipmentAttackSpeedBonus = this.equipmentStats[EAffixType.AttackSpeed] || 0;
    attackInterval = Math.max(0.01, attackInterval - equipmentAttackSpeedBonus);
    
    // 限制攻击间隔在合理范围内（0.1-3秒）
    this.attackSpeed = Math.max(0.01, Math.min(attackInterval, 3.0));
    //console.log("攻击速度:",attackInterval,this.attackSpeed)


    // 5. 暴击率公式
    this.criticalChance = this.config.criticalChance + 
                          this.agility * 0.001 + 
                          this.intelligence * 0.0005;
    
    // 6. 暴击伤害公式
    this.criticalDamage = this.config.criticalDamage + 
                          this.strength * 0.015 + 
                          this.agility * 0.01;

    // 9. 计算命中率
    const baseAccuracy = this.config.accuracy || 0;
    const accuracyFromAgility = this.agility * 0.002;
    const accuracyFromIntelligence = this.intelligence * 0.001;    
    // 基础公式
    this.accuracy = (baseAccuracy + accuracyFromAgility + accuracyFromIntelligence);
    //console.log("playerData accuracy命中计算：",baseAccuracy, accuracyFromAgility,accuracyFromIntelligence,this.accuracy)
    
    
    // 最终数值处理
    //this.accuracy = Util.roundToThree(this.accuracy);      
    
    // 7. 闪避率公式
    this.dodge = Math.max(0, this.config.dodge + this.agility * 0.0005 );
    
    //console.log("this.dodge:",this.dodge)
    // 8. 五行增强（保持不变）
    this.wuxingEnhance = this.config.wuxingEnhance || 0;
    // CDR
    this.CDR = this.intelligence * 0.0005;
    
    
    // 应用装备加成、最终数值处理：百分比的保留两位，非百分比的保留整数
    this.strength = Util.roundToInt(this.strength);
    this.agility = Util.roundToInt(this.agility);
    this.intelligence = Util.roundToInt(this.intelligence);
    this.innerPower = Util.roundToInt(this.innerPower);
    this.vitality = Util.roundToInt(this.vitality);

    console.log("属性异常排查 - 装备加成前最终属性:");
    console.log("属性异常排查 - AP:", apBeforeEquipment, "DP:", dpBeforeEquipment, "HP:", hpBeforeEquipment);
    console.log("属性异常排查 - 装备攻击加成:", this.equipmentStats[EAffixType.Attack], "装备防御加成:", this.equipmentStats[EAffixType.Defense], "装备HP加成:", this.equipmentStats[EAffixType.Hp]);

    this.ap = Util.roundToInt(this.ap +this.equipmentStats[EAffixType.Attack]);
    this.dp = Util.roundToInt(this.dp +this.equipmentStats[EAffixType.Defense]);
    this.hp = Util.roundToInt(this.hp +this.equipmentStats[EAffixType.Hp]);
    this.attackSpeed = Util.roundToTwo(this.attackSpeed+this.equipmentStats[EAffixType.AttackSpeed]);
    this.criticalChance = Util.roundToThree(this.criticalChance+this.equipmentStats[EAffixType.CriticalChance]);
    this.criticalDamage = Util.roundToThree(this.criticalDamage+this.equipmentStats[EAffixType.CriticalDamage]);
    this.accuracy =  Util.roundToThree(this.accuracy+this.equipmentStats[EAffixType.Accuracy]);
    this.attackRange =  Util.roundToInt(this.attackRange+this.equipmentStats[EAffixType.AttackRange]);
    this.ignoreDefense =  Util.roundToThree(this.ignoreDefense+this.equipmentStats[EAffixType.IgnoreDefense]);
    //this.hpRegen =  Util.roundToThree(this.hpRegen+this.equipmentStats[EAffixType.HpRegen]);
    this.moreCoin =  Util.roundToThree(this.moreCoin+this.equipmentStats[EAffixType.Coin]);
    this.moreReown =  Util.roundToThree(this.moreReown+this.equipmentStats[EAffixType.Reown]);
    this.moreExp =  Util.roundToThree(this.moreExp+this.equipmentStats[EAffixType.Exp]);
    this.MF =  Util.roundToThree(this.moreExp+this.equipmentStats[EAffixType.MF]);
    this.wuxingEnhance =  Util.roundToThree(this.wuxingEnhance+this.equipmentStats[EAffixType.WuxingEnhance]);
    this.skillLevel =  Util.roundToThree(this.skillLevel+this.equipmentStats[EAffixType.SkillLevel]);
    this.skill1Level =  Util.roundToInt(this.skill1Level + this.equipmentStats[EAffixType.Skill1Level]);
    this.skill2Level =  Util.roundToInt(this.skill2Level + this.equipmentStats[EAffixType.Skill2Level]);
    this.skill3Level =  Util.roundToInt(this.skill3Level + this.equipmentStats[EAffixType.Skill3Level]);
    this.hpRegen =  Util.roundToThree(this.hpRegen+this.equipmentStats[EAffixType.HpRegen]);
    this.ComboChance =  Util.roundToThree(this.ComboChance+this.equipmentStats[EAffixType.ComboChance]);
    this.skillEnhance = Util.roundToThree(this.skillEnhance+this.equipmentStats[EAffixType.SkillEnhance]);
    this.CDR = Util.roundToThree(this.CDR+this.equipmentStats[EAffixType.CDR]);
    this.dodge = Util.roundToThree(this.dodge+this.equipmentStats[EAffixType.SkillEnhance]);
    this.penetrateCount = Util.roundToInt(this.penetrateCount + this.equipmentStats[EAffixType.PenetrateCount]);
    this.penetratePercent = Util.roundToThree(this.penetratePercent + this.equipmentStats[EAffixType.PenetratePercent]);

    this.rageRegen = Util.roundToThree(this.rageRegen+this.equipmentStats[EAffixType.RageRegen]);
    //限制属性上限
    this.CDR = Math.min(this.CDR,0.5); // 调息缩减最高50%

    // 计算怒气生成 //可能有问题
    // console.log("属性异常排查 - 计算怒气生成之前this.equipmentStats_wuxingStat:", this.equipmentStats_wuxingStats)
    // if(this.equipmentStats_wuxingStats[EAffixType.RageRegen] != undefined){
    //     console.log("属性异常排查 - 计算怒气生成 之前 rageRegen:", this.rageRegen, "增加值:", this.equipmentStats_wuxingStats[EAffixType.RageRegen])
    //     this.rageRegen = this.rageRegen + this.equipmentStats_wuxingStats[EAffixType.RageRegen];
    //     console.log("属性异常排查 - 计算怒气生成 之后 rageRegen:", this.rageRegen)
    // }

    console.log("属性异常排查 - calSecondaryAttribute结束:");
    console.log("属性异常排查 - 最终AP:", this.ap, "最终DP:", this.dp, "最终HP:", this.hp);
    console.log("属性异常排查 - 最终暴击率:", this.criticalChance, "最终暴击伤害:", this.criticalDamage);
    console.log("属性异常排查 - 最终攻速:", this.attackSpeed, "最终命中:", this.accuracy, "最终闪避:", this.dodge);

}

// 计算被动技能加成二级属性，例如丐帮被动技能1，增加会心率10，会心伤害50%
calSecondaryAttributeWithPassiveSkill() {
    if(this.playerType == EPlayerType.Gaibang && this.skillData.assignedPassiveSkill == EPassiveSkill.GaibangPassive1){
    console.log("属性异常排查 - 丐帮被动1加成会心和会伤，加成前： 会心=",this.criticalChance, "会伤=",this.criticalDamage);
    this.criticalChance += 0.1;
    this.criticalDamage += 0.5;
    console.log("属性异常排查 - 丐帮被动1加成会心和会伤，加成后： 会心=",this.criticalChance, "会伤=",this.criticalDamage);

}
    
}

getPackage(): Partial<IPlayerData> {
    return {
        level: this.level,
        exp: this.exp,
        expToNextLevel: this.expToNextLevel,
        attributePoints: this.attributePoints,
        skillPoints: this.skillPoints,

        wuxing: this.wuxing,
        strength: this.strength,
        agility: this.agility,
        intelligence: this.intelligence,
        innerPower: this.innerPower,
        vitality: this.vitality,
        primaryAttribute: this.primaryAttribute,
        ap: this.ap,
        dp: this.dp,
        hp: this.hp,
        accuracy: this.accuracy,
        speed: this.speed,
        attackRange: this.attackRange,
        attackSpeed: this.attackSpeed,
        criticalChance: this.criticalChance,
        criticalDamage: this.criticalDamage,
        wuxingEnhance: this.wuxingEnhance,
        penetrateCount: this.penetrateCount,
        penetratePercent: this.penetratePercent,
        ignoreDefense: this.ignoreDefense,
        skillEnhance: this.skillEnhance,
        ComboChance: this.ComboChance,
        CDR: this.CDR,
        dodge: this.dodge,
        skillLevel: this.skillLevel,
        hpRegen: this.hpRegen,
        skill1Level: this.skill1Level,
        skill2Level: this.skill2Level,
        skill3Level: this.skill3Level,
        
        moreCoin: this.moreCoin,
        moreReown: this.moreReown,
        moreExp: this.moreExp,
        MF: this.MF,

        //ragePerAttack: this.ragePerAttack,
        rageMax: this.rageMax,
        playerType: this.playerType,
        potentialPoints: this.potentialPoints,
        skillDamage: this.skillDamage,

        skillData: this.skillData.getPackage ? this.skillData.getPackage() : undefined,
        equipmentData: this.equipmentData.getPackage ? this.equipmentData.getPackage() : undefined
    };
}

setPackage(data: Partial<IPlayerData>): void {
    if (!data) return;

    const baseProps: (keyof IPlayerData)[] = [
        'level', 'exp', 'expToNextLevel', 'attributePoints', 'skillPoints',
        'wuxing', 'strength', 'agility', 'intelligence', 'innerPower', 'vitality', 
        'primaryAttribute', 'ap', 'dp', 'hp', 'accuracy', 'speed', 'attackRange', 
        'attackSpeed', 'criticalChance', 'criticalDamage', 'wuxingEnhance', 
        'penetrateCount', 'penetratePercent','ignoreDefense', 'skillEnhance', 'ComboChance', 'CDR', 'dodge',
        'skillLevel', 'hpRegen', 'skill1Level', 'skill2Level', 'skill3Level',
        'moreCoin', 'moreReown', 'moreExp', 'MF', 'rageMax', 'playerType',
        'potentialPoints', 'skillDamage'
    ];
    
    baseProps.forEach(prop => {
        if (data[prop] !== undefined) {
            (this as any)[prop] = data[prop];
        }
    });

    if (data.skillData && this.skillData.setPackage) {
        this.skillData.setPackage(data.skillData);
    }
    if (data.equipmentData && this.equipmentData.setPackage) {
        this.equipmentData.setPackage(data.equipmentData);
    }

    this.calculateAttributes();
}

}